package com.ssy.jt808.gateway.client.config;

import com.ssy.gaea.util.JsonMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author zeno
 */
@Configuration
public class JtHttpClientConfig{

  @Bean
  public RestTemplate restTemplate( ClientHttpRequestFactory factory ){
    RestTemplate restTemplate = new RestTemplate(factory);
    List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
    for(HttpMessageConverter<?> messageConverter : messageConverters){
      if( messageConverter instanceof MappingJackson2HttpMessageConverter ){
        MappingJackson2HttpMessageConverter
          jackson2Converter
          = (MappingJackson2HttpMessageConverter)messageConverter;
        jackson2Converter.setObjectMapper(JsonMapper.OBJECT_MAPPER);
      }
    }


    return restTemplate;
  }

  @Bean
  public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
    HttpComponentsClientHttpRequestFactory
      requestFactory
      = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setReadTimeout(20000);
    requestFactory.setConnectTimeout(5000);
    return requestFactory;
  }
}
